﻿using System;
using System.IO;
using System.Net.Http;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SelfMadeMillionaire.BLL.Services;
using SelfMadeMillionaire.Core;
using SelfMadeMillionaire.Core.Entities;
using SelfMadeMillionaire.Core.Enums;
using SelfMadeMillionaire.Core.Repositories;
using SelfMadeMillionaire.DAL;
using SelfMadeMillionaire.DAL.Repositories;
using SelfMadeMillionaire.Core.Services;
using System.Net;
using System.Configuration;

namespace SelfMadeMillioniare.API.Controllers
{
    public class HistoryController : BaseApiController
    {
        public HistoryController()
        {
        }

        public string Test()
        {
            return "test";
        }

        [HttpGet]
        public HttpResponseMessage GetList(string auth_token)
        {
            if (!IsUserAuth(auth_token))
            {
                return Response.CreateErrorResponse("error_auth_token", Request);
            }

            int minAccessLevel = (int)GetMinAccessLevel(auth_token);

            object result = null;

            using (var ctx = new DataContext())
            {
                var news = new NewsletterRepository(ctx);
                var rd = new NewsletterReadService(new NewsletterReadRepository(ctx), new SubscriberRepository(ctx), new NewsletterRepository(ctx));
                result = news.GetAll(x => x.MinAccessLevel <= minAccessLevel).OrderByDescending(n => n.ID).Take(50).ToList().Select(n =>
                        new
                        {
                            ID = n.ID,
                            Title = n.Title,
                            Type = n.IssueType.Title,
                            WasRead = rd.IsRead(n, CurrentUser),
                            Date = n.Date
                        }).ToList();
            }

            return Response.CreateSuccessResponce(result, Request);
                
        }

        [HttpGet]
        public HttpResponseMessage GetDetails(int id, string auth_token)
        {
            if(!IsUserAuth(auth_token))
            {
                return Response.CreateErrorResponse("error_auth_token", Request);
            }


            using (var ctx = new DataContext())
            {
                var news = new NewsletterRepository(ctx);
                var detail = news.Get(id);

                int minAccessLevel = (int)GetMinAccessLevel(auth_token);
                if (detail == null || detail.MinAccessLevel > minAccessLevel)
                    return Response.CreateErrorResponse("access_denied", Request);
                
                var rd = new NewsletterReadService(new NewsletterReadRepository(ctx), new SubscriberRepository(ctx), new NewsletterRepository(ctx));
                rd.MarkRead(detail, new SubscriberRepository(ctx).Get(CurrentUser.ID));


                string pdfLink = Url.Link("ApiWithAction", new { controller = "History", action = "GetNewsletterFile" }) + string.Format("?id={0}&auth_token={1}", detail.ID, auth_token);

                return Response.CreateSuccessResponce
                (
                    new
                    {
                        ID = detail.ID,
                        Title = detail.Title,
                        Type = detail.IssueType.Title,
                        PDF = pdfLink
                    },
                    Request
                );
            }
        }

        [HttpGet]
        public HttpResponseMessage GetNewsletterFile(int id, string auth_token)
        {
            if (!IsUserAuth(auth_token))
            {
                return Response.CreateErrorResponse("error_auth_token", Request);
            }

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            using (var ctx = new DataContext())
            {
                var repo = new NewsletterRepository(ctx);
                var item = repo.Get(id);

                int minAccessLevel = (int)GetMinAccessLevel(auth_token);
                if (item == null || item.MinAccessLevel > minAccessLevel)
                    return Response.CreateErrorResponse("access_denied", Request);

                if ((item.MinAccessLevel > minAccessLevel) && (item.Letter != (byte)ProductType.MaggiesMoneyMountain))
                {
                    return null;
                }
                if (item.IsHide)
                {
                    return null;
                }
                
                string path = Path.Combine(ConfigurationManager.AppSettings["PdfFilesStorePath"], item.PdfFileName);
                if (!File.Exists(path))
                {
                    return Response.CreateErrorResponse("file_not_found", Request);
                }
                var stream = new System.IO.FileStream(path, System.IO.FileMode.Open);

                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
            }

            return response;
        }


    }
}
